﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using Microsoft.Xna.Framework.Graphics;

namespace Babylon.Toolbox
{
    public class ShadersCacheSystem
    {
        readonly Dictionary<Uri, VertexShader> vertexShadersCache = new Dictionary<Uri, VertexShader>();
        readonly Dictionary<Uri, PixelShader> pixelShadersCache = new Dictionary<Uri, PixelShader>();

        internal VertexShader VertexShaderCache { get; set; }
        internal PixelShader PixelShaderCache { get; set; }

        internal VertexShader CompileVertexShader(GraphicsDevice device, Uri shaderUri)
        {
            VertexShader result;
            if (!vertexShadersCache.TryGetValue(shaderUri, out result))
            {
                Stream vertexShaderStream = Application.GetResourceStream(shaderUri).Stream;
                result = VertexShader.FromStream(device, vertexShaderStream);

                vertexShadersCache.Add(shaderUri, result);
            }
            return result;
        }

        internal PixelShader CompilePixelShader(GraphicsDevice device, Uri shaderUri)
        {
            PixelShader result;
            if (!pixelShadersCache.TryGetValue(shaderUri, out result))
            {
                Stream vertexShaderStream = Application.GetResourceStream(shaderUri).Stream;
                result = PixelShader.FromStream(device, vertexShaderStream);

                pixelShadersCache.Add(shaderUri, result);
            }
            return result;
        }
    }
}
